<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

/*敏感词model*/

class SensitiveWord extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';


    protected $table = 'sensitive_word';


    /**
     * 列表
     * @param limit int 分页大小
     * @param keywords string 搜索关键词(文章标题)
     */
    public function lists($keywords = null, $limit = 10)
    {
        $res = $this->select(['id', 'name', 'create_time'])
            ->where(function ($query) use ($keywords) {
                if ($keywords) {
                    $query->where('name', 'like', '%' . $keywords . '%');
                }
            })
            ->orderByDesc('id')
            ->paginate($limit)
            ->toArray();

        return $res;
    }

    /**
     *获取所有的敏感词
     */
    public function getSensitiveWordALL()
    {
        return $this->pluck('name')->toArray();
    }
    /**
     * 添加敏感词
     * @param name string 敏感词名称 多个用 | 拼接
     */
    public function add($data, $field = [])
    {
        $name = explode('|', $data['name']);
        foreach ($name as $v) {
            $res = $this->where('name', $v)->first();
            if (!$res) {
                $obj = new self();
                $obj->name = $v;
                $obj->save();
            }
        }
        return true;
    }
    /**
     * 修改敏感词
     * @param id string 敏感词id
     * @param name string 敏感词名称  (不支持  | 形式)
     */
    public function change($data, $field = [], $findWhere = [])
    {
        $res = $this->where('id', $data['id'])->first();
        $res->name = $data['name'];
        return $res->save();
    }
}
